package com.service.wx.controller;

import com.google.gson.Gson;
import com.service.base.exception.MyException;
import com.service.utils.ResultVo;
import com.service.wx.client.AuthClient;
import com.service.wx.client.UcenterMemberClient;
import com.service.wx.config.WxOpenConfig;
import com.service.wx.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("api/ucenter/wx")
@Controller
@Api(description = "微信登录接口")
public class WxApiController {

    @Autowired
    private WxOpenConfig wxOpenConfig;

    @Autowired
    private UcenterMemberClient ucenterMemberClient;

    @Autowired
    private AuthClient authClient;


    @GetMapping("callback")
    @ApiOperation("微信扫码成功后,获取扫码人信息")
    public String callback(String code, String state,  HttpServletRequest request, HttpServletResponse response) {
        ResultVo resultVo = null;
        try {
            //1 获取code值，临时票据，类似于验证码
            //2 拿着code请求 微信固定的地址，得到两个值 accsess_token 和 openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接三个参数 ：id  秘钥 和 code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    wxOpenConfig.getAppid(),
                    wxOpenConfig.getAppsecret(),
                    code
            );
            //请求这个拼接好的地址，得到返回两个值 accsess_token 和 openid
            //使用httpclient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            //从accessTokenInfo字符串获取出来两个值 accsess_token 和 openid
            //把accessTokenInfo字符串转换map集合，根据map里面key获取对应值
            //使用json转换工具 Gson
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");

            //把扫描人信息添加数据库里面
            //判断数据表里面是否存在相同微信信息，根据openid判断
             resultVo = ucenterMemberClient.verifyOpenId(openid);
            String id = "";
            if (resultVo.getCode() == 20000) {//如果条件为真，表没有相同微信数据，进行添加

                //3 拿着得到accsess_token 和 openid，再去请求微信提供固定的地址，获取到扫描人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //拼接两个参数
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                //发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //获取返回userinfo字符串扫描人信息
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);

                String nickname = (String) userInfoMap.get("nickname");//昵称
                String headimgurl = (String) userInfoMap.get("headimgurl");//头像

                Map<String, Object> param = new HashMap<>();
                param.put("openid", (String) userInfoMap.get("openid"));
                param.put("avatar", headimgurl);
                param.put("nickname", nickname);
                param.put("sex", userInfoMap.get("sex").toString().equals("1") ? "2" : "1");
                resultVo = ucenterMemberClient.wxSave(param);
                if (resultVo.getCode() == 20001) throw new MyException(20001, "登录失败");

                id = resultVo.getData().get("id").toString();

            }else{
                id = resultVo.getData().get("id").toString();
            }
            resultVo = authClient.wxCreateToken(id);
            if (resultVo.getCode() == 20001)  throw new MyException(20001, "登录失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(20001, "登录失败");
        }

        return "redirect:http://www.guli.com?token="+resultVo.getData().get("token");
    }


    @GetMapping("login")
    @ApiOperation("生成微信扫码登录二维码")
    public String login() {
        //%s代表点位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String redirect_uri = null;
        try {
            redirect_uri = URLEncoder.encode(wxOpenConfig.getRedirecturl(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = String.format(baseUrl, wxOpenConfig.getAppid(), redirect_uri, "guli");
        return "redirect:" + url;
    }

}
